package com.gitee.dolt.boot.convert;

import com.gitee.dolt.dozer.DozerUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;

/**
 * @author LYH
 */

public abstract class SuperEntityConvert<Entity, DTO> implements EntityConvert<Entity, DTO> {

    protected Class<Entity> entityClass = null;

    protected Class<DTO> dtoClass = null;

    @Autowired
    protected DozerUtils dozerUtils;

    @Override
    public Entity toEntity(DTO dto) {
        if (getEntityClass().isAssignableFrom(getDtoClass())) {
            return (Entity) dto;
        }
        Entity entity = dozerUtils.map(dto, getEntityClass());
        return entity;
    }

    @Override
    public DTO toDTO(Entity entity) {
        if (getEntityClass().isAssignableFrom(getDtoClass())) {
            return (DTO) entity;
        }
        DTO dto = dozerUtils.map(entity, getDtoClass());
        return dto;
    }

    @Override
    public Entity updateEntity(Entity entity, DTO dto) {
        dozerUtils.map(dto, entity);
        return entity;
    }

    /**
     * 获取entity类型
     *
     * @return
     */
    public Class<Entity> getEntityClass() {
        if (entityClass == null) {
            this.entityClass = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
        return this.entityClass;
    }

    /**
     * 获取dto类型
     *
     * @return
     */
    public Class<DTO> getDtoClass() {
        if (dtoClass == null) {
            this.dtoClass = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        }
        return this.dtoClass;
    }
}
